from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv1D, Flatten, Dropout
from tensorflow.keras.optimizers import Adam
class CustomCNN:
    def __init__(self, input_shape):
        self.model = Sequential([
            Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=input_shape),
            Flatten(),
            Dense(64, activation='relu'),
            Dropout(0.5),
            Dense(1, activation='sigmoid')
        ])

    def compile(self, learning_rate=0.001):
        self.model.compile(
            loss='binary_crossentropy',
            optimizer=Adam(learning_rate=learning_rate),
            metrics=['accuracy']  # 添加 accuracy 指标
        )

    def fit(self, X_train, y_train, epochs=10, batch_size=32,
            validation_data=None, callbacks=None, verbose=1):
        return self.model.fit(
            X_train, y_train,
            epochs=epochs,
            batch_size=batch_size,
            validation_data=validation_data,
            callbacks=callbacks,
            verbose=verbose
        )

    def evaluate(self, X, y, verbose=0):
        result = self.model.evaluate(X, y, verbose=verbose)
        if isinstance(result, list):
            return result  # 返回 [loss, accuracy]
        else:
            return [result]  # 单个指标时包装成列表

    def predict(self, X):
        return (self.model.predict(X) > 0.5).astype(int).flatten()
